using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;

public class UiItemSlot : MonoBehaviour, IPointerDownHandler, IPointerEnterHandler, IPointerExitHandler
{
    protected Image itemImage;
    protected TextMeshProUGUI itemName;
    public InventoryItem Item;
    protected Ui Ui;

    protected virtual void Awake()
    {
        Ui = FindAnyObjectByType<Ui>();
        itemName = GetComponentInChildren<TextMeshProUGUI>();
        itemImage = GetComponent<Image>();
    }

    public void ClearSlot()
    {
        Item = null;
        if (itemImage)
        {
            itemImage.color = Color.clear;
            itemImage.sprite = null;
        }
        itemName.text = string.Empty;
    }

    public void UpdateSlot(InventoryItem item)
    {
        Item = item;
        itemImage.color = Color.white;
        if (Item == null) return;
        itemImage.sprite = Item.data.ItemIcon;
        itemName.text = Item.StackSize > 1 ? Item.StackSize.ToString() : string.Empty;
    }

    public virtual void OnPointerDown(PointerEventData eventData)
    {
        if (Item == null)
            return;
        if (Input.GetKey(KeyCode.LeftControl))
        {
            Inventory.Instance.RemoveItem(Item.data);
            return;
        }

        if (Item.data.ItemType == ItemType.Equipment)
            Inventory.Instance.EquipItem(Item.data);
        Ui.ItemTooltip.Hide();
    }

    public virtual void OnPointerEnter(PointerEventData eventData)
    {
        if (Item == null)
            return;
        Vector2 mousePosition = Input.mousePosition;
        float xOffset;
        float yOffset;
        if (mousePosition.x > 1200)
            xOffset = -250;
        else
            xOffset = 250;
        if (mousePosition.y > 320)
            yOffset = -150;
        else
            yOffset = 150;
        Ui.ItemTooltip.Show(Item.data as ItemDataEquipment);
        Ui.ItemTooltip.transform.position = new Vector3(mousePosition.x + xOffset, mousePosition.y + yOffset);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if (Item == null)
            return;
        Ui.ItemTooltip.Hide();
    }
}